<template>
	<view class="">
		<view class="c_total" id="reply_id">评论 {{ tableTotal }}</view>
		<template v-if="dataList && dataList.length">
			<view class="c_comment" v-for="(item1, index1) in dataList" :key="item1.id">
				<!-- 一级评论 -->
				<CommonComp :data="item1" @likeClick="() => likeClick({ item1, index1 })"
					@replyClick="() => replyClick({ item1, index1 })"
					@deleteClick="() => deleteClick({ item1, index1 })" />

				<view class="children_item" v-if="item1.children > 0">
					<!-- 二级评论 -->
					<CommonComp :id="'reply'+item2.id" v-for="(item2, index2) in item1.childrenShow" :key="item2.id"
						:data="item2" :pData="item1" @likeClick="() => likeClick({ item1, index1, item2, index2 })"
						@replyClick="() => replyClick({ item1, index1, item2, index2 })"
						@deleteClick="() => deleteClick({ item1, index1, item2, index2 })" />
					<!-- 展开折叠的二级评论 -->
					<view v-if="item1.is_expand&&item1.page>0" class="expand_reply" @click="on_expand(index1,item1)">
						<text class="txt">
							展开更多
						</text>
						<uni-icons type="down" size="18" color="#C0C0C0" style="margin-top: 5rpx;"></uni-icons>
					</view>
				</view>

				<view v-if="item1.reply_count>0&&item1.page==0" @click="on_expand(index1,item1)"
					class="children_expand">
					<view class="children_expand_a_c">
						<view class="line"></view>
						<text class="txt">展开{{item1.reply_count}}条回复</text>
					</view>
				</view>

			</view>
		</template>
		<!-- 空盒子 -->
		<view class="empty_box" v-else >
			<uni-icons type="chatboxes" size="36" color="#c0c0c0"></uni-icons>
			<view>
				<span class="txt"> 这里是一片荒草地, </span>
				<span class="txt click" @click="() => newCommentFun()">说点什么...</span>
			</view>
		</view>
		<!-- 评论弹窗 -->
		<uni-popup ref="cPopupRef" type="bottom" @change="popChange">
			<view class="c_popup_box">
				<view class="reply_text">
					<template v-if="Object.keys(replyTemp).length">
						<span class="text_aid">回复给</span>
						<span class="text_main">{{
            replyTemp.item2
              ? replyTemp.item2.nickname
              : replyTemp.item1.nickname
          }}</span>
					</template>
					<span v-else class="text_main">发表新评论</span>
				</view>
				<view class="content">
					<view class="text_area">
						<uni-easyinput class="text_area" type="textarea" v-model="commentValue"
							:placeholder="commentPlaceholder" :focus="focus" trim autoHeight
							maxlength="300"></uni-easyinput>
					</view>
					<view class="send_btn" @tap="() => sendClick()">发送</view>
				</view>
			</view>
		</uni-popup>
		
		<!-- 删除弹窗 -->
		<uni-popup ref="delPopupRef" type="dialog">
			<uni-popup-dialog mode="base" title="" content="确定删除这条评论吗?" :before-close="true" @close="delCloseFun"
				@confirm="delConfirmFun"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script setup>
	import CommonComp from "./componets/common";
	export default {
		components: {
			CommonComp
		},
		props: {
			/** 用户信息
			 *    id: number // 用户id
			 *    nickname: number // 用户名
			 *    user_avatar: string // 用户头像地址
			 */
			userInfo: {
				type: Object,
				default: () => {},
			},
			/** 评论列表
			 *    id: number // 评论id
			 *    parent_id: number // 父级评论id
			 *    reply_id: number // 被回复人评论id
			 *    reply_name: string // 被回复人名称
			 *    nickname: string // 用户名
			 *    user_avatar: string // 评论者头像地址
			 *    contents: string // 评论内容
			 *    is_like: boolean // 是否点赞
			 *    like_count: number // 点赞数统计
			 *    create_time: string // 创建时间
			 */
			tableData: {
				type: Array,
				default: () => [],
			},
			// 评论总数
			tableTotal: {
				type: Number | String,
				default: 0,
			},
			// 评论删除模式
			// bind - 当被删除的一级评论存在回复评论, 那么该评论内容变更显示为[当前评论内容已被移除]
			// only - 仅删除当前评论(后端删除相关联的回复评论, 否则总数显示不对)
			// all - 删除所有评论包括回复评论
			deleteMode: {
				type: String,
				default: "all",
			},

		},
		mounted() {
			this.news_reply = [];
		},



		data() {
			return {
				dataList: [],
				replyTemp: {},
				commentPlaceholder: '说点什么吧！',
				focus: false,
				commentValue: '',
				isNewComment: false,
				delTemp: {}
			}
		},

		watch: {
			tableData: {
				handler(newVal) {
					if (newVal.length !== this.dataList.length) {
						let temp = this.tableData;
						this.dataList = this.treeTransForm(temp);
					}
				},
				deep: true, // 深度监听
				immediate: true // 第一次改变就执行
			}


		},

		methods: {
			// 更多评论文字显示
			expandTxtShow({
				item1,
				index1
			}) {
				return (
					item1.childrenShow &&
					item1.childrenShow.length &&
					item1.children.length - item1.childrenShow.length
				);
			},
			newCommentFun() {
				this.isNewComment = true;
				this.$refs.cPopupRef.open();
			},
			// 数据转换
			treeTransForm(data) {

				let newData = JSON.parse(JSON.stringify(data));
				let result = [];
				let map = {};
				newData.forEach((item, i) => {

					item.owner = item.uid === this.userInfo.uid; // 是否为所有者 所有者可以进行删除 不能回复
					// item.owner = true;

					map[item.id] = item;
				});

				newData.forEach((item) => {
					let parent = map[item.parent_id];

					if (parent) {
						(parent.children || (parent.children = [])).push(item); // 所有回复
						if (parent.children.length === 1) {
							(parent.childrenShow = []).push(item); // 显示的回复
						}
					} else {
						item.childrenShow = [];
						item.children = 0;

						result.push(item);
					}
				});

				return result;
			},
			// 发送评论
			sendClick() {
				let item1 = this.replyTemp.item1
				let index1 = this.replyTemp.index1
				let item2 = this.replyTemp.item2
				let index2 = this.replyTemp.index2
				let item = item2 || item1;
				let params = {};
				// 新评论

				if (this.isNewComment) {
					params = {
						id: Math.random(), // 评论id
						parent_id: 0, // 父级评论id
						reply_id: 0, // 被回复评论id
						reply_name: 0, // 被回复人名称
						reply_uid: 0
					};
				} else {
					// 回复评论
					let parent_id = item.parent_id > 0 ? item.parent_id : item.id;



					params = {
						id: Math.random(), // 评论id
						parent_id: parent_id, // 父级评论id
						reply_id: parent_id == item.id ? 0 : item.id, // 被回复评论id
						reply_name: parent_id == item.id ? '' : item.nickname, // 被回复人名称
						reply_uid: parent_id == item.id ? 0 : item.uid
					};
					console.log("params: " + JSON.stringify(params));


				}


				params = {
					...params,
					nickname: this.userInfo.nickname, // 用户名
					uid: this.userInfo.uid,
					face: this.userInfo.face, //  用户头像地址
					contents: this.commentValue, //  用户评论内容
					is_like: false, // 是否点赞
					like_count: 0, // 点赞数统计
					create_time: Date.now() / 1000, // 创建时间
					owner: true, // 是否为所有者 所有者可以进行删除 管理员默认true
				};

				uni.showLoading({
					title: "正在发送",
					mask: true,
				});
				this.$emit("replyFun", {
					params
				}, (res) => {

					uni.hideLoading();
					if (res == 0) {
						return
					}
					params = {
						...params,
						id: res.id
					};
					// 新评论
					if (this.isNewComment) {
						//放在第一个
						params.childrenShow = [];
						params.children = 0;

						this.dataList.unshift(params);

						setTimeout(() => {
							this.$nextTick(function() {
								uni.pageScrollTo({
									duration: 200,
									selector: "#reply_id" //滚动到的元素的id
								})

							})
						}, 100)

					} else {
						// 回复
						let c_data = this.dataList[index1];


						c_data.childrenShow.push(params);
						c_data.children = c_data.childrenShow.length;
						//不显示展示更多回复
						if (c_data.reply_count == 0) {

						} else {
							c_data.reply_count++
						}

						setTimeout(() => {
							this.$nextTick(function() {
								uni.pageScrollTo({
									duration: 200,
									selector: "#reply" + params.id //滚动到的元素的id
								})

							})
						}, 200)
					}
					//自己发布的 记录下 获取新的 删除已有的 以免id冲突
					this.news_reply.push(params);




					this.$emit("tableTotal", this.tableTotal + 1);
					this.$refs.cPopupRef.close();
				});




			},

			likeClick({
				item1,
				index1,
				item2,
				index2
			}) {
				let item = item2 || item1;
				this.$emit("likeFun", {
					params: item
				}, (res) => {
					if (res == 200) {
						this.setLike(item);
					}
				});
			},
			// 首次展开更多评论
			on_expand(index1, item1) {
				uni.showLoading({
					title: '加载中...',
					mask: true

				})
				item1.page++
				this.$emit("first_expand", {
					params: item1
				}, (res) => {
					if (res != 0) {


						for (var i = 0; i < this.news_reply.length; i++) {
							res = res.filter(t => t.id != this.news_reply[i]['id']);
						}



						this.dataList[index1].childrenShow = this.dataList[index1].childrenShow.concat(res);
						this.dataList[index1].children = res.length;
						//当获取的 大于当前页数 则证明还有回复 
						if (res.length >= 20) {
							this.dataList[index1].is_expand = true;
						} else {
							this.dataList[index1].is_expand = false;
						}
					}
					uni.hideLoading()
				});

			},
			// // 展开更多评论
			// expandReplyFun({
			// 	item1,
			// 	index1
			// }) {

			// 	let csLen = this.dataList[index1].childrenShow.length;
			// 	this.dataList[index1].childrenShow.push(
			// 		...this.dataList[index1].children.slice(csLen, csLen + 6) // 截取5条评论
			// 	);
			// },
			// 删除
			deleteClick(item1, index1, item2, index2) {

				this.delTemp = JSON.parse(JSON.stringify({
					item1,
					index1,
					item2,
					index2
				}));


				this.$refs.delPopupRef.open();
			},
			replyClick({
				item1,
				index1,
				item2,
				index2
			}) {
				this.replyTemp = JSON.parse(JSON.stringify({
					item1,
					index1,
					item2,
					index2
				}));

				this.$refs.cPopupRef.open();
			},
			// 评论弹窗
			popChange(e) {
				// 关闭弹窗
				if (!e.show) {
					this.commentValue = ""; // 清空输入框值
					this.replyTemp = {}; // 清空被回复人信息
					this.isNewComment = false; // 恢复是否为新评论默认值
				}
				this.focus = e.show;
			},
			// 点赞
			setLike(item) {
				item.is_like = !item.is_like;

				item.like_count = item.is_like ? item.like_count + 1 : item.like_count - 1;
			},
			// 关闭删除弹窗
			delCloseFun() {
				this.delTemp = {};
				this.$refs.delPopupRef.close();
			},
			// 确定删除
			delConfirmFun() {

				let index1 = this.delTemp.item1.index1
				let item1 = this.delTemp.item1.item1
				let index2 = this.delTemp.item1.index2
				let item2 = this.delTemp.item1.item2

				let c_data = this.dataList[index1];




				uni.showLoading({
					title: "正在删除",
					mask: true,
				});

				// 删除二级评论

				if (index2 >= 0) {
					this.$emit("deleteFun", {
						params: [c_data.childrenShow[index2].id]
					}, (res) => {

						uni.hideLoading();
						if (res == 200) {
							this.$emit("tableTotal", this.tableTotal - 1);
							c_data.childrenShow.splice(index2, 1);
							c_data.children = c_data.childrenShow.length;
							c_data.reply_count--

						}

					});
				} else {

					// 删除一级评论
					if (c_data.children > 0) {
						// 如果一级评论包含回复评论
						switch (this.deleteMode) {
							case "bind":
								// 一级评论内容展示修改为: 当前评论内容已被移除
								c_data.contents = "当前评论内容已被移除";
								break;
							case "only":
								// 后端自行根据删除的一级评论id, 查找关联的子评论进行删除
								this.$emit(
									"deleteFun", {
										mode: this.deleteMode,
										params: [c_data.id],
									},
									(res) => {

										uni.hideLoading();
										if (res == 200) {
											this.$emit("tableTotal", this.tableTotal - 1);
											this.dataList.splice(index1, 1);
										}
									}
								);
								break;
							default:
								// all
								// 收集子评论id, 提交给后端统一删除
								let delIdArr = [c_data.id];
								c_data.childrenShow.forEach((_, i) => {
									delIdArr.push(_.id);
								});
								this.$emit(
									"deleteFun", {
										params: delIdArr,
										mode: this.deleteMode
									},
									(res) => {
										uni.hideLoading();
										if (res == 200) {
											this.$emit("tableTotal", this.tableTotal - 1);
											this.dataList.splice(index1, 1);
										}


									}
								);
								break;
						}
					} else {
						// 一级评论无回复, 直接删除
						this.$emit("deleteFun", {
							params: [c_data.id]
						}, (res) => {

							uni.hideLoading();
							if (res == 200) {
								this.$emit("tableTotal", this.tableTotal - 1);
								this.dataList.splice(index1, 1);
							}

						});
					}
				}
				this.delCloseFun();
			}


		}
	}
</script>

<style lang="scss" scoped>
	////////////////////////
	.center {
		display: flex;
		align-items: center;
	}

	////////////////////////
	.c_total {
		padding: 20rpx 30rpx 0 30rpx;
		font-size: 28rpx;
	}

	.empty_box {
		display: flex;
		justify-content: center;
		align-items: center;
		flex-direction: column;
		padding: 150rpx 10rpx;
		font-size: 28rpx;

		.txt {

			color: $uni-text-color-disable;
		}

		.click {
			color: $uni-color-primary;
		}
	}

	.c_comment {
		padding: 20rpx 30rpx;
		font-size: 28rpx;

		.children_item {
			padding: 20rpx 30rpx;
			margin-top: 10rpx;
			margin-left: 80rpx;


			.expand_reply {
				margin-top: 10rpx;

				margin-left: 80rpx;
				display: flex;
				align-items: center;

				.txt {
					font-size: 28rpx;
					color: $uni-color-primary;
				}
			}
		}

		.children_expand {
			margin-left: 80rpx;
			padding-top: 20rpx;

			.children_expand_a_c {
				display: flex;
				align-items: center;

				.txt {
					margin-left: 10rpx;
					font-size: 28rpx;
					color: $uni-color-primary;
				}

				.line {
					background-color: $uni-color-primary;
					height: 3rpx;
					width: 60rpx;
				}
			}


		}
	}

	.c_popup_box {
		background-color: #fff;

		.reply_text {
			@extend .center;
			padding: 20rpx 20rpx 0 20rpx;
			font-size: 26rpx;

			.text_aid {
				color: $uni-text-color-grey;
				margin-right: 5rpx;
			}

			.text_main {}
		}

		.content {
			@extend .center;

			.text_area {
				flex: 1;
				padding: 20rpx;
			}

			.send_btn {
				@extend .center;
				justify-content: center;
				width: 120rpx;
				height: 60rpx;
				border-radius: 20rpx;
				font-size: 28rpx;
				color: #fff;
				background-color: $uni-color-primary;
				margin-right: 20rpx;
			}
		}
	}
</style>